import 'dart:io';

import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:flutter_base_library/config/HttpConfig.dart';
import 'package:flutter_base_library/http/interceptor/LogInterceptor.dart';
import 'package:flutter_base_library/http/interceptor/TokenInterceptor.dart';
import 'package:flutter_base_library/log/log.dart';

class Http {
  Http._internal(); //类的私有的命名构造方法

  // 初始化默认配置
  static HttpDioConfig httpDioConfig = HttpDioConfig();

  ///网络请求配置
  static Dio dio;

  ///初始化dio
  static init({
    HttpDioConfig config,
  }) {
    if (config != null) {
      httpDioConfig = config;
    }

    dio = new Dio(BaseOptions(
      baseUrl: httpDioConfig.baseUrl.toString(),
      connectTimeout: httpDioConfig.connectTimeout,
      receiveTimeout: httpDioConfig.receiveTimeout,
    ));

    ///初始化cookie
    // PathUtils.getDocumentsDirPath().then((value) {
    //   var cookieJar = PersistCookieJar(dir: (value + "/.cookies/"));
    //   dio.interceptors.add(CookieManager(cookieJar));
    // });

    //添加拦截器
    // dio.interceptors.add(httpDioConfig.headerInterceptor);
    if (httpDioConfig.headerInterceptor != null) {
      dio.interceptors.add(httpDioConfig.headerInterceptor);
    }
    dio.interceptors
        .add(httpDioConfig.tokenInterceptor ?? new TokenInterceptor());

    (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
        (client) {
      client.badCertificateCallback =
          (X509Certificate cert, String host, int port) {
        return Platform.isAndroid;
      };
      if (httpDioConfig.isNeedProxy) {
        print("==========================设置代理===============");

        client.findProxy = (uri) {
          return httpDioConfig.proxyHost;
        };
      }
    };
    dio.interceptors.add(httpDioConfig.logInterceptor ?? new LogsInterceptor());
    if (httpDioConfig.interceptors != null &&
        httpDioConfig.interceptors.isNotEmpty) {
      dio.interceptors.addAll(httpDioConfig.interceptors);
    }
  }

  static addHeaders(Map<String, dynamic> headers) {
    dio.options.headers = headers;
    return dio;
  }

  /// http request methods
  static const String GET = 'get';
  static const String POST = 'post';
  static const String PUT = 'put';
  static const String PATCH = 'patch';
  static const String DELETE = 'delete';

  ///error统一处理
  static void handleError(DioError e) {
    switch (e.type) {
      case DioErrorType.CONNECT_TIMEOUT:
        print("连接超时");
        break;
      case DioErrorType.SEND_TIMEOUT:
        print("请求超时");
        break;
      case DioErrorType.RECEIVE_TIMEOUT:
        print("响应超时");
        break;
      case DioErrorType.RESPONSE:
        print("出现异常");
        break;
      case DioErrorType.CANCEL:
        print("请求取消");
        break;
      default:
        print("未知错误");
        break;
    }
  }

  ///get请求
  static Future get(String url, Map<String, dynamic> params,{Options options,int connectTimeOut}) async {
    Response response;
    print("超时时长设置的是"+connectTimeOut.toString()+"<===>"+httpDioConfig.connectTimeout.toString());
    dio.options.connectTimeout=connectTimeOut==0?httpDioConfig.connectTimeout:connectTimeOut;
    print("超时时长设置hhhh的是"+dio.options.connectTimeout.toString()+"==="+dio.options.baseUrl);

    if (params != null) {
      response = await dio.get(url, queryParameters: params,options: options);
    } else {
      response = await dio.get(url,options: options);
    }
    return response;
  }

  ///post 表单请求
  static Future post(
    String url,
    Map<String, dynamic> params,
  {int connectTimeOut}
  ) async {
    print("超时时长设置的是"+connectTimeOut.toString()+"<===>"+httpDioConfig.connectTimeout.toString());
    dio.options.connectTimeout=connectTimeOut==0?httpDioConfig.connectTimeout:connectTimeOut;
    print("超时时长设置hhhh的是"+dio.options.connectTimeout.toString()+"==="+dio.options.baseUrl);
    Response response;
    try {
      response = await dio.post(url, queryParameters: params);
    } catch (e) {
      handleError(e);
    }
    return response?.data;
  }

  ///post body请求
  static Future postJson(String url, [Map<String, dynamic> data,int connectTimeOut=0]) async {
    print("超时时长设置的是"+connectTimeOut.toString()+"<===>"+httpDioConfig.connectTimeout.toString());
    dio.options.connectTimeout=connectTimeOut==0?httpDioConfig.connectTimeout:connectTimeOut;
    print("超时时长设置hhhh的是"+dio.options.connectTimeout.toString()+"==="+dio.options.baseUrl);
    Response response = await dio.post(url, data: data);
    return response?.data;
  }

  ///下载文件
  static Future downloadFile(urlPath, savePath) async {
    Response response;
    try {
      response = await dio.download(urlPath, savePath,
          onReceiveProgress: (int count, int total) {
        //进度
        print("$count $total");
      });
    } on DioError catch (e) {
      handleError(e);
    }
    return response?.data;
  }

  static Future downloadFile2(urlPath, savePath,
      {ProgressCallback onReceiveProgress}) async {
    Response response;
    try {
      response = await dio.download(urlPath, savePath,
          onReceiveProgress: onReceiveProgress == null
              ? (int count, int total) {
                  //进度
                  print("$count $total");
                }
              : onReceiveProgress);
    } on DioError catch (e) {
      handleError(e);
    }
    return response;
  }
}
